import { to } from 'await-to-js';
import defAva from '@/assets/images/profile.png';
import store from '@/store';
import { getToken, removeToken, setToken,getSydToken,setSydToken,removeSydToken } from '@/utils/auth';
import { login as loginApi, logout as logoutApi, getInfo as getUserInfo, getMerchantProviderAPI } from '@/api/login';
import { LoginData } from '@/api/types';
import { LoginTypeEnum } from '@/enums/RespEnum';

function timeTip() {
  const currentHour = new Date().getHours();


  // 定义一天中的时间段
  const MORNING_START = 0; // 凌晨开始
  const MORNING_END = 9;   // 早上结束
  const NOON = 11;         // 中午
  const AFTERNOON_END = 13; // 下午开始
  const EVENING_END = 20;   // 晚上开始

  // 根据当前小时返回对应的问候语
  if (currentHour >= MORNING_START && currentHour < MORNING_END) {
    return "早上好"; // 0-8点
  } else if (currentHour >= MORNING_END && currentHour < AFTERNOON_END - 1) {
    return "上午好"; // 特殊处理11点和12点为上午好
  } else if (currentHour >= AFTERNOON_END && currentHour < EVENING_END) {
    return "下午好"; // 13-19点
  } else if (currentHour >= EVENING_END) {
    return "晚上好"; // 20点及以后
  }
  return "你好";
}

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const name = ref('');
  const userInfo = ref<any>({});
  const nickname = ref('');
  const userId = ref<string | number>('');
  const avatar = ref('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const curRoleId = ref<string | number>('');
  const isReadProt = ref<1 | 0>(0); // 是否阅读平台使用协议(0:否 1:是)
  const isResetPass = ref();
  const defaultProvider = ref(getSydToken());
  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    const [err, res] = await to(loginApi(userInfo));
    if (res) {
      const data = res.data;
      setToken(data.access_token);
      token.value = data.access_token;
      ElNotification.success({
        title: '欢迎',
        message: `${timeTip()}, 欢迎回来`,
        duration: 5000,
      })
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  const setPlatFormToken = (inputToken: string) => {
    setToken(inputToken);
    token.value = inputToken;
  };

  const getMerchantProvider = async (userName: string): Promise<any> => {
    const [err, res] = await to(getMerchantProviderAPI({ userName }));
    if (res) {
      return Promise.resolve(res);
    }
    return Promise.reject(err);
  };

  // 获取验证方式

  const validateCode = async (userInfo: LoginData): Promise<any> => {
    return Promise.resolve({ validateCode: Math.random() > 0.5 ? LoginTypeEnum.MESSAGE : LoginTypeEnum.WE_CHAT });
  };

  // 获取用户信息
  const getInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfo());
    if (res) {
      const data = res.data;
      const user = data.user;
      const profile = user.avatar == '' || user.avatar == null ? defAva : user.avatar;

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
        permissions.value = data.permissions;
      } else {
        if(data.permissions && data.permissions.length > 0){
            permissions.value = data.permissions;
        }
        roles.value = ['ROLE_DEFAULT'];
      }



      userInfo.value = user;
      name.value = user.userName;
      nickname.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      curRoleId.value = user.curRoleId;
      isReadProt.value = user.isReadProt;
      isResetPass.value = user.isResetPass;
      userInfo.value = user;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = '';
    roles.value = [];
    permissions.value = [];
    removeToken();
    removeSydToken();
  };

  const setAvatar = (value: string) => {
    avatar.value = value;
  };

  const setDefaultProvider = (data) => {
    defaultProvider.value = data;
    setSydToken(data)
  };

  return {
    userId,
    token,
    userInfo,
    curRoleId,
    nickname,
    avatar,
    roles,
    permissions,
    login,
    getInfo,
    logout,
    setAvatar,
    getMerchantProvider,
    validateCode,
    isReadProt,
    isResetPass,
    setPlatFormToken,
    setDefaultProvider,
    defaultProvider
  };
});

export default useUserStore;
// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
